#include "vector.h"
template<class T>
clx::vector<T>::vector()
  :_start(nullptr)
  ,_finish(nullptr)
  ,_endofstorage(nullptr)
{}
  
template<class T>
size_t clx::vector<T>::size() const
{
  return _finish - _start;
}

template<class T>
size_t clx::vector<T>::capacity() const
{
  return _endofstorage - _start;
}

template<class T>
void clx::vector<T>::reserve(size_t n) 
{
  if (n > capacity())
  {
    iterator tmp = new T[n];
    size_t sz = size();
    if (_start)
    {
      memcpy(tmp, _start, sizeof(T) * sz);
      delete[] _start;
    }
    _start = tmp;
    _finish = tmp + sz;
    _endofstorage = tmp + n;
  }
}

template<class T>
void clx::vector<T>::resize(size_t n, T val) 
{
  if (n < size())
  {
    _finish = _start + n;
  }
  else 
  {
    if ( n > capacity())
    {
      reserve(n);
    }
    while (_finish != _endofstorage)
   {
      *_finish = val;
      ++_finish;
    }
  }
}
template<class T>
void clx::vector<T>::push_back(const T& x)
{
  if (_finish == _endofstorage)
  {
    size_t newcapacity = capacity() == 0 ? 4 : 2 * capacity();
    reserve(newcapacity);
  }
  *_finish = x;
  _finish++;

}

template<class T>
void clx::vector<T>::pop_back()
{
  assert(size() > 0);
  _finish--;
}

template<class T>
void clx::print_vector(const vector<T> v)
{
  vector<int>::const_iterator it = v.begin();
  while (it != v.end())
  {
    cout << *it << " ";
    it++;
  }
  cout << endl;
  
}

void clx::vector_test1()
{
  vector<int> v;
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);
  v.push_back(4);
  v.push_back(5);
  vector<int>::iterator it = v.begin();
  while (it != v.end())
  {
    cout << *it << " ";
    it++;
  }
  cout << endl;
  
}

void clx::vector_test2() 
{
  vector<int> v;
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);
  v.push_back(4);
  v.push_back(5);
  clx::print_vector(v);
  v.resize(2);
  clx::print_vector(v);
  v.resize(3);
  clx::print_vector(v);
  v.resize(10);
  clx::print_vector(v);

}

template<class T>
void clx::vector<T>::insert(iterator pos, const T& x)
{
  size_t sz = pos - _start;
  if (_finish == _endofstorage)
  {
    size_t newcapacity = capacity() == 0 ? 4 : 2 * capacity();
    reserve(newcapacity);
  }
  iterator end = _finish -1;
  while (end >= _start + sz)
  {
    *(end + 1) = *(end);
    end--;
  }
  *(sz + _start) = x;
  ++_finish;

}

void clx::vector_test3()
{
  vector<int> v;
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);
  v.push_back(4);
  vector<int>::iterator pos = find(v.begin(), v.end(), 3);
  clx::print_vector(v);
  v.insert(pos, 30);
  clx::print_vector(v);
  pos = find(v.begin(), v.end(), 4);
  v.insert(pos, 40);
  clx::print_vector(v);
  pos = find(v.begin(), v.end(), 1);
  v.insert(pos, 10);
  clx::print_vector(v);

}















